import { useAxios } from '@vueuse/integrations/useAxios';
import axios, { AxiosRequestConfig } from 'axios';
import Toast from 'vant/lib/toast';
import 'vant/es/toast/style';
import { useUserStore } from "/src/store/modules/user";
import {Notify} from "vant";
// const userStore = useUserStore();

// create an axios instance
const instance = axios.create({
  withCredentials: false,
  baseURL: '',
  timeout: 15000,
  // 修改请求数据
  transformRequest: [function (data, headers) {
    // console.log('headers',headers)
    let ret = ''
    for (let it in data) {
      // 去除空字符串的请求字段
      if (data[it] !== '') {
        if (ret !== '') ret += '&'
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it])
      }
    }
    return ret
  }],
});

// request interceptor
instance.interceptors.request.use(
  (config) => {
    // do something before request is sent
    // const token = store.state.user.token;

    const userStore =  useUserStore();
    const token = userStore.getUserToken
    if ('' != userStore.getUserToken || null == userStore.getUserToken) {
      console.log('userStore.getUserToken',userStore.getUserToken)
      config.headers.token = userStore.getUserToken
      // let each request carry token
      // config.headers = {
      //   ...config.headers,
      //   'token': userStore.getUserToken
      // };
    }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  },
);

// response interceptor
instance.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data;
    // if the custom code is not 200, it is judged as an error.
    if (res.code !== 200) {
      Notify({ type: 'danger',background: '#ee0a24', message: `请求失败，${res.msg}` });
      // Toast.fail(`请求失败，${res.msg}`);
      // 412: Token expired;
      if (res.code === 401 ) {
        alert("身份超时，请重新进入")
        // store.dispatch('user/userLogout');
      }
      return Promise.reject(res.msg || 'Error') ;
    } else {
      // console.log('res:',res)
      // console.log('res:',response.headers.token)
      if(null != response.headers.token){
        const userStore =  useUserStore();
        userStore.setUserToken(response.headers.token)
      }
      return res;
    }
  },
  (error) => {
    console.log('err' + error);
    // Toast(error.message);
    Notify({ type: 'danger',background: '#ee0a24', message: `请求失败，${res.msg}` });
    // Toast.fail(`请求失败，${res.msg}`);
    return Promise.reject(error.message);
  },
);

/**
 * reactive useFetchApi
 */

export default function useAxiosApi(url: string, config: AxiosRequestConfig) {
  return useAxios(url, config, instance);
}
